package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.BaseContext;
import com.reggie.entity.ShoppingCart;
import com.reggie.mapper.ShoppingCartMapper;
import com.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    /**
     * 添加购物车
     * @param shoppingCart
     */
    public ShoppingCart shopadd(ShoppingCart shoppingCart) {
        //看看是菜品 还是套餐
        //设置用户id 把购物车里面的东西和用户绑定起来才知道是他点的
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //添加之前 要看看购物车里面是否已经存在 如果存在就要number+1
        //如果不存在就要新建
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        //只看用户名旗下的
        lqw.eq(ShoppingCart::getUserId,shoppingCart.getUserId());
        //判断是菜品还是套餐
        if(shoppingCart.getDishId()!=null){
            //是菜品时 看看有误菜品id相同的
            lqw.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else{
            //是套餐时传过来的东西被限制了 只可能是这两种数据
            lqw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        //看看当前菜品或者套餐 是否在购物车里面
        ShoppingCart cart = super.getOne(lqw);
        if(cart!=null){
            //已经存在 所以数量+1
            cart.setNumber(cart.getNumber()+1);
            super.updateById(cart);
        }else {
            //不存在 需要新建
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            super.save(shoppingCart);
            cart = shoppingCart;
        }
        return cart;

    }
}
